import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Image } from 'antd';
import styles from './index.less';

/**
 * 图片展示组件
 * @param {String} url 图片路径
 * @param {String} type 展示类型 image 图片形式
 */
const PopImgShow = ({ url, width = 40, onClick, type = 'image', previewDom, children }) => {
  PopImgShow.propTypes = {
    url: PropTypes.string,
  };

  const [visible, setVisible] = useState(false);

  const imgDiv = (
    <div
      onClick={onClick}
      style={{
        cursor: 'pointer',
        width: width,
        height: width,
        borderRadius: 4,
        marginRight: 8,
        backgroundImage: `url(${url})`,
        display: 'inline-block',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
      }}
    ></div>
  );

  const imageComponents = (
    <Image
      key={url}
      width={width}
      height={width}
      src={url || 'error'}
      className={styles.descript_img}
      fallback=""
      preview={{
        visible,
        src: url,
        onVisibleChange: (value) => setVisible(value),
      }}
    />
  );

  const showDom = {
    image: onClick ? imgDiv : imageComponents, // 默认图片展示
    // 自定义图片预览
    previewImg: (
      <>
        <div style={{ display: 'inline-block' }} onClick={() => setVisible(true)}>
          {previewDom}
        </div>
        {imageComponents}
      </>
    ),
  }[type];

  return (
    // 自定义预览时不显示图片
    <div className={`${styles.showImgClass} ${type === 'previewImg' && styles.hiddenImg}`}>
      {showDom}
      {children && <div style={{ display: 'inline-block', flex: 1 }}>{children}</div>}
    </div>
  );
};

export default PopImgShow;
